package com.mjlf.akka.simple;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

/**
 * @ClassName BecomeDemo
 * @auther mjlf
 * @Date 2019/8/5 13:23
 * @Description 练习使用become方法
 */
public class BecomeDemo {

    static class BecomeActor extends AbstractActor{

        int count = 0;

        Receive receiveA = receiveBuilder().matchAny(msg -> {
            count ++;
            if(count >= 2){
                getContext().unbecome();
            }else {
                System.out.println("A : " + msg);
            }
        }).build();

        Receive receiveB = receiveBuilder().matchAny( msg -> {
            if(msg.equals("A")){
                //转到使用receiveA处理
                getContext().become(receiveA, false);
            }else {
                System.out.println("B : " + msg);
            }
        }).build();

        @Override
        public Receive createReceive() {
            return receiveBuilder().matchAny( msg ->{
                if(msg.equals("B")){
                    getContext().become(receiveB, false);
                }else {
                    System.out.println("R : " + msg);
                }
            }).build();
        }
    }

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create();
        ActorRef becomeActor = system.actorOf(Props.create(BecomeActor.class));

        becomeActor.tell("A", ActorRef.noSender());
        becomeActor.tell("B", ActorRef.noSender());
        becomeActor.tell("C", ActorRef.noSender());
        becomeActor.tell("D", ActorRef.noSender());
        becomeActor.tell("A", ActorRef.noSender());
        becomeActor.tell("A", ActorRef.noSender());
        becomeActor.tell("A", ActorRef.noSender());
        becomeActor.tell("A", ActorRef.noSender());
        becomeActor.tell("A", ActorRef.noSender());
        becomeActor.tell("A", ActorRef.noSender());
    }
}
